<script setup lang="ts">
import { OrderState } from '@/api/constants'
import { orderStateList } from '@/api/constants'
import {
  getOrderList,
  getPayMock,
  getWxPayMiniParams,
  putOrderReceiptById,
  delOrderByIds,
} from '@/api/order'
import type { OrderItem } from '@/types/order'
import type { OrderListParams } from '@/types/order'
import { onMounted, ref } from 'vue'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 定义 porps
const props = defineProps<{
  orderState: number
}>()

// 请求参数
const queryParams: OrderListParams = {
  page: 1,
  pageSize: 5,
  orderState: props.orderState,
}

// 标记是否最后一页数据
const isFinish = ref(false)
// 标记是否加载·完成
const isLoading = ref(false)

// 获取订单列表
const orderList = ref<OrderItem[]>([])
const getMemberOrderData = async () => {
  if (isLoading.value) return
  // 判断是否最后一页数据
  if (isFinish.value) {
    return uni.showToast({
      title: '没有更多了',
      icon: 'none',
    })
  }

  isLoading.value = true
  // 获取数据
  const res = await getOrderList(queryParams)
  orderList.value = [...orderList.value, ...res.result.items]

  isLoading.value = false
  // 更新页签
  if (queryParams.page! < res.result.pages) {
    queryParams.page!++
  } else {
    isFinish.value = true
  }
}

// 下拉
const onScrollToLower = () => {
  console.log(111)

  getMemberOrderData()
}

const isTriggered = ref(false)

// 下拉刷新
const onRefresherrefresh = async () => {
  // 开始动画
  isTriggered.value = true
  // 重置数据
  queryParams.page = 1
  orderList.value = []
  isFinish.value = false
  // 加载数据
  await getMemberOrderData()
  // 关闭动画
  isTriggered.value = false
}

// 支付订单
const onPayOrder = async (id: string) => {
  // 开发环境模拟支付
  if (import.meta.env.DEV) {
    await getPayMock({ orderId: id })
  } else {
    // #ifdef MP-WEIXIN
    // 正式环境微信支付
    const res = await getWxPayMiniParams({ orderId: id })
    await wx.requestPayment(res.result)
    // #endif

    // #ifdef H5 || APP-PLUS
    // H5端 和 App 端未开通支付-模拟支付体验
    await getPayMock({ orderId: id })
    // #endif
  }

  // 成功提示
  uni.showToast({ title: '支付成功' })
  // 更新订单状态
  const order = orderList.value.find((v) => v.id === id)
  order!.orderState = OrderState.DaiFaHuo
}

// 确认收货
const onOrderConfirm = async (id: string) => {
  uni.showModal({
    content: '为保障您的权益，请收到货并确认无误后，再确认收货',
    success: async ({ confirm }) => {
      if (confirm) {
        const res = await putOrderReceiptById(id)
        const order = orderList.value.find((v) => v.id === id)
        order!.orderState = OrderState.DaiPingJia
        uni.showToast({ title: '收货成功', icon: 'success' })
      }
    },
  })
}

// 删除订单
const delOrder = async (id: string) => {
  uni.showModal({
    content: '确定删除该订单吗？',
    success: async ({ confirm }) => {
      if (confirm) {
        await delOrderByIds({ ids: [id] })
        // 前端页面删除
        const index = orderList.value.findIndex((v) => v.id === id)
        orderList.value.splice(index, 1)
      }
    },
  })
}

onMounted(() => {
  getMemberOrderData()
})
</script>

<template>
  <scroll-view
    enable-back-to-top
    scroll-y
    class="orders"
    refresher-enabled
    :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresherrefresh"
    @scrolltolower="onScrollToLower"
  >
    <view class="card" v-for="order in orderList" :key="order.id">
      <!-- 订单信息 -->
      <view class="status">
        <text class="date">{{ order.createTime }}</text>
        <!-- 订单状态文字 -->
        <text>{{ orderStateList[order.orderState].text }}</text>
        <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
        <text
          v-if="order.orderState >= OrderState.DaiPingJia"
          class="icon-delete"
          @tap="delOrder(order.id)"
        ></text>
      </view>
      <!-- 商品信息，点击商品跳转到订单详情，不是商品详情 -->
      <navigator
        v-for="item in order.skus"
        :key="item.id"
        class="goods"
        :url="`/pagesOrder/detail/detail?id=${order.id}`"
        hover-class="none"
      >
        <view class="cover">
          <image mode="aspectFit" :src="item.image"></image>
        </view>
        <view class="meta">
          <view class="name ellipsis">{{ item.name }}</view>
          <view class="type">{{ item.attrsText }}</view>
        </view>
      </navigator>
      <!-- 支付信息 -->
      <view class="payment">
        <text class="quantity">共{{ order.totalNum }}件商品</text>
        <text>实付</text>
        <text class="amount"> <text class="symbol">¥</text>{{ order.payMoney }}</text>
      </view>
      <!-- 订单操作按钮 -->
      <view class="action">
        <!-- 待付款状态：显示去支付按钮 -->
        <template v-if="order.orderState === OrderState.DaiFuKuan">
          <view class="button primary" @tap="onPayOrder(order.id)">去支付</view>
        </template>
        <template v-else>
          <navigator
            class="button secondary"
            :url="`/pagesOrder/create/create?orderId=id`"
            hover-class="none"
          >
            再次购买
          </navigator>
          <!-- 待收货状态: 展示确认收货 -->
          <view
            v-if="order.orderState === OrderState.DaiShouHuo"
            class="button primary"
            @tap="onOrderConfirm(order.id)"
            >确认收货</view
          >
        </template>
      </view>
    </view>
    <!-- 底部提示文字 -->
    <view class="loading-text" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      {{ true ? '没有更多数据~' : '正在加载...' }}
    </view>
  </scroll-view>
</template>
